package com.yh.workbill.adapter;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.yh.workbill.R;
import com.yh.workbill.databinding.ItemCountBinding;
import com.yh.workbill.model.Count;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;

public class CountAdapter extends RecyclerView.Adapter<CountAdapter.ViewHolder> {

    private List<Count> data;

    private OnItemClick onItemClick;

    public void setOnItemClick(OnItemClick onItemClick) {
        this.onItemClick = onItemClick;
    }

    public CountAdapter(List<Count> data) {
        this.data = data;
    }

    public void setData(List<Count> data) {
        this.data = data;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ItemCountBinding view = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.item_count, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Count count = data.get(position);
        holder.getBinding().setData(count);
        holder.itemView.setOnClickListener(v -> {
            if (onItemClick != null) {
                onItemClick.onItem(count, position);
            }
        });
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        ItemCountBinding binding;

        public ViewHolder(@NonNull ItemCountBinding itemView) {
            super(itemView.getRoot());
            binding = itemView;
        }

        public ItemCountBinding getBinding() {
            return binding;
        }
    }

    public interface OnItemClick {
        void onItem(Count count, int position);
    }
}
